package com.itheima.tanhua.autoconfig.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.tanhua.autoconfig.properties.OssProperties;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class OssTemplate {

    private String accessKeyId;

    private String accessKeySecret;

    private String bucketName;

    private String url;

    private String endpoint;

    public OssTemplate(OssProperties ossProperties) {
        this.accessKeyId = ossProperties.getAccessKey();
        this.accessKeySecret = ossProperties.getSecret();
        this.bucketName = ossProperties.getBucketName();
        this.endpoint = ossProperties.getEndpoint();
        this.url = ossProperties.getUrl();
    }

    public String upload(String suffixName, InputStream is) {
        String filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID().toString() + "." + suffixName;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.putObject(bucketName, filename, is);

        ossClient.shutdown();

        return url + "/" + filename;
    }
}
